<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class QueueController extends Controller
{
    /**
     * @param Request $request
     * @return JsonResponse
     * 添加技能组
     */
    public function addAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $request->get('vcc_code', 0);
        $que_name = $request->get('que_name', 0);
        $que_tag = $request->get('que_tag', '');
        $que_type = $request->get('que_type', 0);
        $que_length = $request->get('que_length', 10);
        $que_time = $request->get('que_time', 120);
        $ring_time = $request->get('ring_time', 30);
        $next_wait = $request->get('next_wait', 5);
        $b_announce = $request->get('b_announce', 0);
        $noans_times = $request->get('noans_times', 3);
        $noans_wait = $request->get('noans_wait', 10);
        $wait_audio = $request->get('wait_audio', '');
        $noans_action = $request->get('noans_action', '1');
        $que_strategy = $request->get('que_strategy', 1);
        $win_ip = $this->container->getParameter('win_ip'); //通信服务器IP
        $port = $this->container->getParameter('win_socket_port');

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //技能组验证
        $msg = $this->get('validator.custom')->isEmptyName($que_name);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        //技能组名称重复
        $where = " vcc_id = :vcc_id AND que_name = :que_name AND is_del = 0";
        $par_arr = array('vcc_id'=>$vid, 'que_name'=>$que_name);
        $msg = $this->get('validator.custom')->existQue($where, $par_arr, 404);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        //查看最大坐席数
        $ques = $conn->fetchColumn(
            'SELECT groups '.
            'FROM cc_ccods '.
            'WHERE vcc_id = :vcc_id ',
            array('vcc_id'=>$vid)
        );

        $alreay = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_queue '.
            'WHERE vcc_id = :vcc_id AND is_del = 0',
            array('vcc_id'=>$vid)
        );

        if ($alreay >= $ques && !empty($ques)) {
            $ret = array(
                'code' => 407,
                'message' => '技能组数量达到上限',
            );
            return new JsonResponse($ret);
        }

        $data = array(
            'vcc_id' => $vid,
            'que_name' => $que_name,
            'que_tag' => $que_tag,
            'que_type' => $que_type,
            'que_length' => $que_length,
            'que_time' => $que_time,
            'ring_time' => $ring_time,
            'next_wait' => $next_wait,
            'b_announce' => $b_announce,
            'noans_times' => $noans_times,
            'noans_wait' => $noans_wait,
            'wait_audio' => $wait_audio,
            'que_strategy' => $que_strategy,
            'noans_action' => in_array($noans_action, array(0, 1, 2)) ? $noans_action : 1,
        );
        try {
            $conn->insert('win_queue', $data);
            //插入成功之后；重载技能组；
            $ret = $this->get('validator.custom')->wintelsReload($vid, $win_ip, $port, 406);
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $ret = array(
                'code' => 405,
                'message' => '添加技能组失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * 编辑技能组
     */
    public function updateAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $request->get('vcc_code', 0);
        $que_name = $request->get('que_name', 0);
        $que_tag = $request->get('que_tag', '');
        $que_type = $request->get('que_type', 0);
        $que_length = $request->get('que_length', 10);
        $que_time = $request->get('que_time', 120);
        $ring_time = $request->get('ring_time', 30);
        $next_wait = $request->get('next_wait', 5);
        $b_announce = $request->get('b_announce', 0);
        $noans_times = $request->get('noans_times', 3);
        $noans_wait = $request->get('noans_wait', 10);
        $noans_action = $request->get('noans_action', '1');
        $wait_audio = $request->get('wait_audio', '');
        $que_strategy = $request->get('que_strategy', 1);

        $que_id = $request->get('que_id', 0);
        $win_ip = $this->container->getParameter('win_ip'); //通信服务器IP
        $port = $this->container->getParameter('win_socket_port');

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //技能组验证
        $msg = $this->get('validator.custom')->isEmptyName($que_name);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }


        //验证技能组id 是否属于该企业；
        $msg = $this->get('validator.custom')->vccQue($vid, $que_id);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        //技能组名称重复
        $where = " vcc_id = :vcc_id AND que_name = :que_name AND id <> :que_id AND is_del = 0";
        $par_arr = array('vcc_id'=>$vid, 'que_name'=>$que_name, 'que_id' => $que_id);
        $msg = $this->get('validator.custom')->existQue($where, $par_arr);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        //开始修改入库
        $data = array(
            'que_name' => $que_name,
            'que_tag' => $que_tag,
            'que_type' => $que_type,
            'que_length' => $que_length,
            'que_time' => $que_time,
            'ring_time' => $ring_time,
            'next_wait' => $next_wait,
            'b_announce' => $b_announce,
            'noans_times' => $noans_times,
            'noans_wait' => $noans_wait,
            'wait_audio' => $wait_audio,
            'que_strategy' => $que_strategy,
            'noans_action' => in_array($noans_action, array(0, 1, 2)) ? $noans_action : 1,
        );
        try {
            $conn->update('win_queue', $data, array('vcc_id'=>$vid, 'id'=>$que_id));
            $ret = $this->get('validator.custom')->wintelsReload($vid, $win_ip, $port, 407);
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $ret = array(
                'code' => 406,
                'message' => '编辑技能组失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * @param $vcc_code
     * @param $que_id
     * @param $flag (1代表确认，0，需要验证是否有坐席)
     * @return JsonResponse
     * 删除技能组
     */
    public function deleteAction($vcc_code, $que_id, $flag)
    {
        //vcc_code 验证
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        $win_ip = $this->container->getParameter('win_ip'); //通信服务器IP
        $port = $this->container->getParameter('win_socket_port');
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //有批量删除情况
        $que_arr = json_decode($que_id);
        $que_arr = json_last_error() || !is_array($que_arr) ? array((int)$que_id) : $que_arr;
        if (empty($que_arr)) {
            return new JsonResponse(array('code'=>407, 'message'=>'技能组id为空'));
        }

        $errorMsg = array();
        foreach ($que_arr as $que_id) {

            //验证技能组id 是否属于该企业；
            $msg = $this->get('validator.custom')->vccQue($vid, $que_id, 403);
            if (!empty($msg)) {
                $errorMsg[] = array_merge($msg, array('que_id'=>$que_id));
                continue;
            }

            //验证技能组下是否有坐席；
            if (!$flag) {
                $count = $conn->fetchColumn(
                    'SELECT count(*) '.
                    'FROM win_agqu '.
                    'WHERE que_id = :que_id ',
                    array('que_id'=>$que_id)
                );
                if (!empty($count)) {
                    $errorMsg[] = array('code'=>404,'message'=>'技能组下面有坐席','que_id'=>$que_id);
                    continue;
                }
            }
            try {
                $conn->delete('win_agqu', array('que_id'=>$que_id));
                $conn->update('win_queue', array('is_del'=>1), array('vcc_id'=>$vid, 'id'=>$que_id));
                //删除技能组也需要重载技能组；
                $ret = $this->get('validator.custom')->wintelsReload($vid, $win_ip, $port, 406);
                $errorMsg[] = array_merge($ret, array('que_id'=>$que_id));
            } catch (Exception $e) {
                $errorMsg[] = array(
                    'code' => 405,
                    'message' => '删除技能组失败['.$e->getMessage().']',
                    'que_id' => $que_id
                );
            }
        }
        return new JsonResponse(array('code'=>500,'message'=>'总结果','data'=>$errorMsg));
    }

    /**
     * @param $vcc_code
     * @param $info
     * @return JsonResponse
     * 获得技能组列表
     */

    public function listAction($vcc_code, $info)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 404, 'message'=>'info格式非json'));
            }
        }
        $where = '';
        if (isset($addInfo['filter'])) {
            if (isset($addInfo['filter']['que_id'])) {
                //验证技能组
                $msg = $this->get('validator.custom')->vccQue($vid, $addInfo['filter']['que_id'], 403);
                if (!empty($msg)) {
                    return new JsonResponse($msg);
                }

            }
            $where = isset($addInfo['filter']['que_id']) && !empty($addInfo['filter']['que_id']) ? " AND w.id = '".(int)$addInfo['filter']['que_id']."'" : '';
            $where.= isset($addInfo['filter']['que_name']) && !empty($addInfo['filter']['que_name']) ? " AND que_name like '%".$addInfo['filter']['que_name']."%'" : '';
        }
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_queue as w '.
            'WHERE vcc_id = :vcc_id AND is_del = 0 '.$where,
            array('vcc_id'=>$vid)
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_queue', $addInfo);
        $page['sort'] = $page['sort'] !=1 ? 'w.'.$page['sort'] : $page['sort'];
        $list = $conn->fetchAll(
            'SELECT que_name,que_tag,que_type,que_length,que_time,ring_time,next_wait,b_announce,noans_times,'.
            'noans_wait,w.id,que_strategy,noans_action,wait_audio,s.name as sound_name '.
            'FROM win_queue as w LEFT JOIN win_sounds as s ON w.wait_audio = s.id '.
            'WHERE w.vcc_id = :vcc_id AND w.is_del = 0 '.$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vcc_id'=>$vid)
        );
        $ret = array(
            'code' => 200,
            'message' =>'ok',
            'total' => $count,
            'data' => $list,
        );
        return new JsonResponse($ret);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * 技能组分配坐席
     */
    public function assignAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $request->get('vcc_code', 0);
        $que_id = $request->get('que_id', 0);
        $agents = $request->get('agents', 0);

        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证技能组id 是否属于该企业；
        if (!empty($que_id)) {
            $msg = $this->get('validator.custom')->vccQue($vid, $que_id, 403);
            if (!empty($msg)) {
                return new JsonResponse($msg);
            }
        } else {
            $ret = array('code' => 404, 'message'=>'技能组ID为空');
            return new JsonResponse($ret);
        }

        //验证agents 是否为空
        $msg = $this->get('validator.custom')->isEmptyName($agents, 409, 'agents参数为空');
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证agents
        $row = json_decode($agents, true);
        if (json_last_error()) {
            $ret = array('code' => 405, 'message'=>'agents非JSON格式');
            return new JsonResponse($ret);
        }
        $error_msg = array();
        foreach ($row as $v) {
            if (isset($v['ag_id']) && isset($v['skill'])) {
                //先判断ag_id 是否属于该企业；
                $count =  $conn->fetchColumn(
                    'SELECT count(*) '.
                    'FROM win_agent '.
                    'WHERE vcc_id = :vcc_id AND id = :ag_id ',
                    array('vcc_id'=>$vid, 'ag_id'=>$v['ag_id'])
                );
                if (!$count) {
                    $error_msg[] = array(
                        'code' => '406',
                        'message' => 'ag_id 不属于该企业',
                        'data' => $v,
                    );
                    continue;
                }

                //再判断该坐席是否分配了
                $total =  $conn->fetchColumn(
                    'SELECT count(*) '.
                    'FROM win_agqu '.
                    'WHERE que_id = :que_id AND ag_id = :ag_id ',
                    array('que_id'=>$que_id, 'ag_id'=>$v['ag_id'])
                );

                if ($total) {
                    $error_msg[] = array(
                        'code' => '407',
                        'message' => '坐席已经分配技能组',
                        'data' => $v,
                    );
                    continue;
                }

                //写入到数据库
                $data = array('que_id'=>$que_id, 'ag_id'=>$v['ag_id'], 'skill'=>$v['skill']);
                try {
                    $conn->insert('win_agqu', $data);
                    $error_msg[] = array('code'=>'200','message'=>'ok','data'=>$v);
                } catch (Exception $e) {
                    $error_msg[] = array(
                        'code' => '408',
                        'message' => '分配失败 ['.$e->getMessage().']',
                    );
                }
            }
        }
        //总结果
        $ret = array(
            'code' => '500',
            'message' => '总结果',
            'data' => $error_msg,
        );
        return new JsonResponse($ret);
    }

    public function cancelAssignAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $request->get('vcc_code', 0);
        $que_id = $request->get('que_id', 0);
        $agents = $request->get('agents', 0);

        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证技能组id 是否属于该企业；
        if (!empty($que_id)) {
            $msg = $this->get('validator.custom')->vccQue($vid, $que_id, 403);
            if (!empty($msg)) {
                return new JsonResponse($msg);
            }
        } else {
            $ret = array('code' => 404, 'message'=>'技能组ID为空');
            return new JsonResponse($ret);
        }

        //验证agents 是否为空
        $msg = $this->get('validator.custom')->isEmptyName($agents, 405, 'agents参数为空');
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证agents
        $row = json_decode($agents, true);
        if (json_last_error()) {
            $ret = array('code' => 406, 'message'=>'agents非JSON格式');
            return new JsonResponse($ret);
        }
        is_array($row) ? array_push($row, 0) : $row = array(0);
        //删除
        $temp = array();
        foreach ($row as $v) {
            $temp[] = (int)$v;
        }
        $temp = array_unique($temp);
        $agents = implode(',', $temp);
        $conn->executeQuery(
            "DELETE FROM win_agqu WHERE que_id = :que_id AND ag_id IN ($agents)",
            array('que_id'=>$que_id)
        );
        return new JsonResponse(array('code'=>200, 'message'=>'ok'));
    }
}
